package impl

import (
	"context"
	"database/sql"
	"pd/conf"
	"pd/modules"
	"pd/modules/allowed_requrl"
	"pd/utils"

	log "github.com/marmotedu/iam/pkg/log"
)

var (
	// 实例是否实现接口的静态检查
	_    allowed_requrl.Service = (*ArImpl)(nil)
	impl                        = &ArImpl{}
)

// allowed_requrl 的业务实例
type ArImpl struct {
	db *sql.DB
	l  log.Logger
}

// Deprecated: Use ImplConfig and init
func NewArImpl() *ArImpl {
	return &ArImpl{
		db: conf.C().Mysql.GetDB(),
		l:  log.WithName(allowed_requrl.AppName),
	}
}

func (i *ArImpl) CreateAllowed_requrl(ctx context.Context, ins *allowed_requrl.Allowed_requrl) (
	*allowed_requrl.Allowed_requrl, error) {
	// 第一步校验数据合法性
	if err := utils.ValidateName(ins.Name); err != nil {
		return nil, err
	}
	// 第二步默认值填充
	ins.InjectDefualt()
	// 第三步，插入数据到数据库中并保存
	if err := i.saveAllowed_requrl(ctx, ins); err != nil {
		i.l.Errorf("%v insert field ,%v", ins.Name, err)
		return nil, err
	}
	i.l.Infof("%v insert success", ins.Name)
	return ins, nil
}

func (ar *ArImpl) ImplConfig() {
	ar.db = conf.C().Mysql.GetDB()
	ar.l = log.WithName(allowed_requrl.AppName)
}

func (ar *ArImpl) ImplName() string {
	return allowed_requrl.AppName
}

func init() {
	modules.RegistryImpls(impl)
}
